import React, {useEffect, useState} from 'react';
import ProForm, { ProFormText} from "@ant-design/pro-form";
import {message, Modal, Skeleton} from "antd";
import {addLabels,getLabelDetail,updateLabel} from "@/services/label";

const CreateOrEdit = (props) => {
  const { visible,editId,showModal,refs} = props;

  const type = editId !== undefined ? "编辑" : "添加"
  const [formObj] = ProForm.useForm()
  // 初始化数据列表 定义设置状态
  const [initialValues,setInitialValues] = useState(undefined);

  // 更新 打开显示模态框 获取标签数据
  useEffect(async () => {
    if (editId !== undefined) {
      const Detail = await getLabelDetail(editId)
      setInitialValues(Detail.data)
    }
  },[])
  // 执行添加
  const handleSubmit = async (data) => {
    if(data.id){
      const res = await updateLabel(data.id, data)
      if (res.status == undefined) {
        message.success("修改成功")
        showModal(false)
        refs.current.reload();
      }else{
        message.error('修改失败')
      }
    }else{
      const res = await addLabels(data)
      console.log(res);
      if(res.status == null) {
        showModal(false)
        message.success("添加标签成功")
        refs.current.reload();
        showModal(false)
      } else {
        message.error('添加标签失败')
      }
    }
  }

  return(
    <Modal
      title={type +"列表"}
      visible={visible}
      onCancel={() => showModal(false)}
      footer={false}
      destroyOnClose={true}
    >
      {
        initialValues === undefined && editId !== undefined ? <Skeleton/> :
          <ProForm
            form={formObj}
            onFinish={(data) => handleSubmit(data)}
            initialValues={initialValues}>
            <ProFormText
              name="id"
              hidden={true}
            />
            <ProFormText
              label="名称"
              name="name"
              rules={[
                {
                  required: true
                }
              ]}
            />
            <ProFormText
              label="排序"
              name="order"
              rules={[
                {
                  required: true
                }
              ]}
            />
          </ProForm>
      }


    </Modal>
  );
};

export default CreateOrEdit;
